/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package jwu2.core;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import jwu2.log.Logger;
import jwu2.net.ConnectionFactory;
import lombok.Cleanup;

/**
 *
 * @author Rolf
 */
public class AddonUtils {

    /**
     * Downloads an addon from a given url, returning a file object corresponding
     * to the downloaded file
     * @param url
     * @return
     */
    public static File downloadAddon(Addon a, Task downloadTask) {
        try {
            File tmpDownloadFile = File.createTempFile("jwu", ".zip");

            @Cleanup BufferedReader in = ConnectionFactory.getReaderFromURLNoCache(a.getDownloadUrl());
            @Cleanup FileWriter out = new FileWriter(tmpDownloadFile);

            char[] buffer = new char[1024 * 8];

            int length = in.read(buffer, 0, buffer.length);

            while(length != -1) {
                out.write(buffer, 0, length);
                length = in.read(buffer, 0, buffer.length);
            }

            return tmpDownloadFile;

        } catch (Exception ex) {
            Logger.logln("Error downloading addon zip: "+ex);
        }

        return null;
    }
    
    /**
     * Installs the latest version of the given addon
     * @param a
     */
    public static void installAddon(Addon a) {
        Task installAddonTask = Task.createTask("Install addon ["+a+"]");
        Task downloadAddonTask = installAddonTask.createSubTask("Download addon ["+a+"]");
        Task unpackAddonTask = installAddonTask.createSubTask("Unpack ["+a+"]");
        Task deleteBeforeUpdateTask = null;
        if( Config.singleton().shouldDeleteBeforeUpdate() ) {
            deleteBeforeUpdateTask = installAddonTask.createSubTask("Delete before update ["+a+"]");
        }
        Task moveAddonToInterfaceTask = installAddonTask.createSubTask("Move addon to interface folder ["+a+"]");
        
        File addonZip = downloadAddon(a, downloadAddonTask);
        downloadAddonTask.setComplete();
        
        File destination = new File("sandbox/");
        destination.mkdirs();
        
        List<String> addonDirectories = unpackZip(addonZip, destination, unpackAddonTask);
        unpackAddonTask.setComplete();
        
        updateAddonWithDirectories(a, addonDirectories);
        
        if( Config.singleton().shouldDeleteBeforeUpdate() ) {
            deleteAddon(a, deleteBeforeUpdateTask);
            deleteBeforeUpdateTask.setComplete();
        }
        
        moveAddonToInterfaceFolder(a, moveAddonToInterfaceTask);
        moveAddonToInterfaceTask.setComplete();
    }

    /**
     * Clears the interface folder of this addon
     * @param a
     * @param deleteTask
     */
    private static void deleteAddon(Addon a, Task deleteTask) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    /**
     * Moves the addon to the real Interface folder
     * @param a
     * @param moveTask
     */
    private static void moveAddonToInterfaceFolder(Addon a, Task moveTask) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    /**
     * Unpacks the given zip file to the given destination
     * @param addonZip
     * @param unzipTask
     * @return
     */
    private static List<String> unpackZip(File addonZip, File destination, Task unzipTask) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    /**
     * Updates the addon with new addonDirectories
     * @param a
     * @param addonDirectories
     */
    private static void updateAddonWithDirectories(Addon a, List<String> addonDirectories) {
        a.getAddonDirectories().clear();
        
        for(String dir : addonDirectories) {
            a.addAddonDirectory(dir);
        }
    }
}
